<!--
  * 控制地图
  *
  * @Author:    骆伟林
  * @Date:      2025-10-21 17:51:27
-->
<template>
  <div class="map-container">
    <div id="container" ref="mapContainer"></div>
    <a-button @click="toggleDrawer" type="primary" class="toggle-button1"> <MenuUnfoldOutlined />搜索点位</a-button>
    <div style="display: flex; align-items: center" class="toggle-button">
      <div style="display: flex; align-items: center">
        <table style="margin-right: 10px">
          <tr>
            <td>
              <a-input-search id="tipinput" v-model:value="address" placeholder="请输入地址" />
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
  <TimeForm ref="timeForm" />
  <searchDrawer v-if="showDrawer" class="search-drawer" @getTarget="getTarget" />
</template>
<script setup>
  import { ref, onMounted, onUnmounted, computed, watch } from 'vue';
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { pictureApi } from '/@/api/business/picture/picture-api';
  import TimeForm from './components/control-map-time-form.vue';
  import searchDrawer from './components/controlMap-search.vue';
  const address = ref('');
  let map = null;
  let AMapInstance = null;
  let mouseTool = null;
  let placeSearch = null; // 地点搜索实例
  let autoComplete = null; // 自动完成实例
  let currentOverlay = null;
  let lightMarker = ref(null);
  let lightMarkers = [];

  // 初始化地图
  const initMap = async () => {
    const container = document.getElementById('container');
    if (!container) {
      console.error('Map container div not exist');
      return;
    }
    window._AMapSecurityConfig = {
      securityJsCode: '8c81168d00a5521156969ba6f9302035',
    };

    try {
      const AMap = await AMapLoader.load({
        key: '8a22a89acfe4e990d7e50ed0862b3bc3',
        version: '2.0',
        plugins: [
          'AMap.MouseTool',
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.HawkEye',
          'AMap.ControlBar',
          'AMap.Geometry',
          'AMap.AutoComplete',
          'AMap.PlaceSearch',
          'AMap.Marker',
          'AMap.InfoWindow',
        ],
      });

      AMapInstance = AMap;
      map = new AMap.Map('container', {
        center: [104.777664, 29.332199],
        zoom: 17,
        viewMode: '2D',
        pitch: 30,
      });

      // 添加控件
      const scale = new AMap.Scale();
      map.addControl(scale);

      autoComplete = new AMapInstance.AutoComplete({
        input: 'tipinput',
      });
      autoComplete.on('select', select);

      placeSearch = new AMapInstance.PlaceSearch({
        map: map,
      });

      const toolBar = new AMap.ToolBar({
        position: {
          top: '110px',
          right: '40px',
        },
      });
      map.addControl(toolBar);

      // 地图初始化完成后加载标记
      await loadAndDisplayMarkers();
    } catch (error) {
      console.error('地图初始化失败:', error);
    }
  };

  // 加载并显示所有标记
  const loadAndDisplayMarkers = async () => {
    const markersData = await fetchMarkers();
    if (Array.isArray(markersData)) {
      markersData.forEach((markerInfo) => {
        addMarker(markerInfo);
      });
    } else {
      console.error('接口返回的数据不是数组:', markersData);
    }
  };
  // 处理选择
  const select = (e) => {
    if (e.poi && e.poi.adcode && e.poi.name) {
      const { adcode, name } = e.poi;
      placeSearch.setCity(adcode);
      placeSearch.search(name);
    }
  };

  // 113.390345,22.527096 113.276946,22.534067
  // 调用接口获取标记数据
  const fetchMarkers = async () => {
    try {
      const res = await pictureApi.getAddressList();
      return res.data;
    } catch (err) {
      console.error('获取标记数据失败:', err);
      return [];
    }
  };

  // 创建并显示信息窗体
  const showInfoWindow = (lightInfo, position) => {
    if (!map || !AMapInstance) return;

    // 创建信息窗体内容
    const infoWindowContent = document.createElement('div');
    infoWindowContent.innerHTML = `
    <div>
      <div>
        <b>地点名称：${lightInfo.addressName}</b>
        <a style="color: #2b8cbe;cursor: pointer;float:right;" class="detail">查看全景图</a>
      </div>
    </div>
  `;

    // 绑定详情按钮事件
    const detailButton = infoWindowContent.querySelector('.detail');
    if (detailButton) {
      detailButton.addEventListener('click', (event) => {
        lightDetail(lightInfo);
      });
    }

    // 创建信息窗体
    const infoWindow = new AMapInstance.InfoWindow({
      content: infoWindowContent,
      offset: new AMapInstance.Pixel(0, -30),
    });
    // 显示信息窗体
    infoWindow.open(map, position);
  };

  // 添加单个标记到地图
  const addMarker = (markerInfo) => {
    if (!map || !AMapInstance) return;

    const marker = new AMapInstance.Marker({
      position: [markerInfo.longitude, markerInfo.latitude],
      title: markerInfo.addressName,
      map: map,
    });

    // 绑定标记点击事件
    marker.on('click', () => {
      showInfoWindow(markerInfo, marker.getPosition());
    });
  };

  const timeForm = ref(null);
  //获取地点的全景图数据
  async function lightDetail(lightInfo) {
    const res = await pictureApi.getPictureByAddressId(lightInfo.addressId);
    console.log(res);
    timeForm.value.show(res.data);
    //根据res.data每个数据的pictureTime，限制时间组件可选的点
  }

  const showDrawer = ref(false);
  const toggleDrawer = () => {
    showDrawer.value = !showDrawer.value;
  };
  function getTarget(data) {
    map.setCenter([data.longitude, data.latitude]);
  }
  onMounted(async () => {
    await initMap();
    await loadAndDisplayMarkers();
  });

  onUnmounted(() => {
    console.log(map);

    map.destroy();
    map = null;
    console.log(map);
  });
</script>

<style scoped>
  .map-container {
    position: relative;
    width: 100%;
    height: 100vh;
  }

  #container {
    width: 100%;
    height: 100%;
  }

  .toggle-button {
    position: absolute;
    top: 10px;
    left: 40%;
  }

  .search-drawer {
    position: absolute;
    top: 7%;
    left: 0;
    width: 300px;
    height: 100%;
    background-color: white;
    box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
    padding: 20px;
  }
  .detail {
    color: #2b8cbe;
    cursor: pointer;
    float: right;
  }
  .tree-control {
    position: absolute;
    top: 0;
    right: 20px;
    z-index: 5;
  }
  .toggle-button1 {
    position: absolute;
    top: 1%;
    left: 20px;
  }
</style>
